package com.qf.service;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.qf.model.StandardReport;
import com.qf.model.StandardSubmit;
import org.elasticsearch.action.index.IndexRequest;
import org.elasticsearch.action.index.IndexResponse;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.action.update.UpdateRequest;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.RangeQueryBuilder;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.histogram.Histogram;
import org.elasticsearch.search.builder.SearchSourceBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.springframework.amqp.core.QueueBuilder;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.text.SimpleDateFormat;
import java.util.*;

/**
 * @author Zwnan
 */
@Service
public class SearchServiceImpl implements SearchService {

    @Autowired
    private ObjectMapper objectMapper;
    @Value("${log-index}")
    private String index;

    @Autowired
    private RestHighLevelClient restHighLevelClient;

    @Override
    public void saveLog(StandardSubmit submit)throws Exception{
        String name = index + new SimpleDateFormat("yyyy").format(new Date());
        IndexRequest request = new IndexRequest();
        request.index(name);
        request.id(submit.getSequenceId());
        request.source(objectMapper.writeValueAsString(submit));

        IndexResponse index = restHighLevelClient.index(request, RequestOptions.DEFAULT);
    }

    @Override
    public void updateLog(StandardReport report) throws Exception {

        String name = report+new SimpleDateFormat("yyyy").format(new Date());

        UpdateRequest request = new UpdateRequest();
        request.index(name);
        request.id(report.getSequenceId());
        Map<String,Object> source = new HashMap<>();
        source.put("reportState",report.getState());
        source.put("errorCode", report.getErrorCode());
        request.doc(source);
        restHighLevelClient.update(request,RequestOptions.DEFAULT);

    }

    @Override
    public Long searchCount(Map counts) throws Exception{
        SearchResponse searchResponse = getSearchResponse(counts);
        long count = searchResponse.getHits().getTotalHits().value;

        return count;
    }

    @Override
    public List<Map> searchLogs(Map counts) throws Exception{

        SearchResponse searchResponse = getSearchResponse(counts);
        List<Map> data = new ArrayList<>();
        for (SearchHit hit : searchResponse.getHits().getHits()) {
            Map<String,Object> source = hit.getSourceAsMap();
            HighlightField messageContentField = hit.getHighlightFields().get("messageContent");
            if (messageContentField != null){
                String content = messageContentField.fragments()[0].string();
                source.put("messageContent", content);
            }
            data.add(source);
        }
        return data;
    }

    @Override
    public Map<String, Long> statSendStatus(Map parameter)throws Exception {
        String indexName = index + new SimpleDateFormat("yyyy").format(new Date());

        SearchRequest request = new SearchRequest();
        request.indices(indexName);

        SearchSourceBuilder sourceBuilder = new SearchSourceBuilder();

        sourceBuilder.aggregation(AggregationBuilders.histogram("agg").field("reportState").interval(1));
        BoolQueryBuilder boolQuery = QueryBuilders.boolQuery();
        Integer clientID = (Integer) parameter.get("clientID");
        if(clientID != null){
            boolQuery.must(QueryBuilders.termQuery("clientID",clientID));
        }
        // startTime开始时间,endTime结束时间
        Long startTime = (Long) parameter.get("startTime");
        Long endTime = (Long) parameter.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(startTime != null){
            rangeQuery.gte(startTime);
        }
        if(endTime != null){
            rangeQuery.lte(endTime);
        }
        boolQuery.must(rangeQuery);
        sourceBuilder.query(boolQuery);
        // 将sourceBuilder设置给request
        request.source(sourceBuilder);
        SearchResponse resp = restHighLevelClient.search(request, RequestOptions.DEFAULT);
        Aggregations aggregations = resp.getAggregations();
        Histogram agg = aggregations.get("agg");
        List<? extends Histogram.Bucket> buckets = agg.getBuckets();
        //5. 封装数据
        Map<String, Long> data = new HashMap<>();
        for (Histogram.Bucket bucket : buckets) {
            Double key = (Double) bucket.getKey();
            if(key == 0.0){
                // 短信发送成功
                data.put("0",bucket.getDocCount());
            }else if(key == 1.0){
                //短信发送失败
                data.put("1",bucket.getDocCount());
            }else{
                //短信未返回状态
                data.put("2",bucket.getDocCount());
            }
        }
        //6. 返回
        return data;
    }


    private SearchResponse getSearchResponse(Map counts) throws Exception{

        String name = index + new SimpleDateFormat("yyyy").format(new Date());
        SearchRequest request = new SearchRequest();
        request.indices(name);
        SearchSourceBuilder builder = new SearchSourceBuilder();
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();
        Integer clientID = (Integer) counts.get("clientID");
        if (null !=clientID){
            queryBuilder.must(QueryBuilders.termQuery("clientID", clientID));
        }
        String keyword = (String) counts.get("keyword");
        if(!StringUtils.isEmpty(keyword)){
            queryBuilder.must(QueryBuilders.matchQuery("messageContent",keyword));
        }
        String mobile = (String) counts.get("mobile");
        if(!StringUtils.isEmpty(mobile)){
            queryBuilder.must(QueryBuilders.termQuery("destMobile",mobile));
        }
        Long startTime = (Long) counts.get("startTime");
        Long endTime = (Long) counts.get("endTime");
        RangeQueryBuilder rangeQuery = QueryBuilders.rangeQuery("sendTime");
        if(startTime != null){
            rangeQuery.gte(startTime);
        }
        if(endTime != null){
            rangeQuery.lte(endTime);
        }
        queryBuilder.must(rangeQuery);
        // 设置给sourceBuilder
        builder.query(queryBuilder);

        Integer start = (Integer) counts.get("start");
        Integer rows = (Integer) counts.get("rows");
        builder.from(start);
        builder.size(rows);

        HighlightBuilder highlightBuilder = new HighlightBuilder();
        highlightBuilder.field("messageContent");
        highlightBuilder.preTags((String) counts.get("highLightPreTag"));
        highlightBuilder.postTags((String) counts.get("highLightPostTag"));
        builder.highlighter(highlightBuilder);

        request.source(builder);

        return restHighLevelClient.search(request, RequestOptions.DEFAULT);
    }



}
